const express = require('express')
const path = require('path')
// 系统用户集合（表）
const userManage = require(path.join(__dirname, '../../models/back_manage/user.js'))
// 客户端用户
const userClient = require(path.join(__dirname, '../../models/music_db/user_manage.js'))
// 歌手集合
const songerManage = require(path.join(__dirname, '../../models/back_manage/songer.js'))
// 歌单集合
const songListManage = require(path.join(__dirname, '../../models/back_manage/songList.js'))
// 歌曲集合
const songManage = require(path.join(__dirname, '../../models/back_manage/song.js'))
// 轮播图集合
const carouselManage = require(path.join(__dirname, '../../models/back_manage/carousel.js'))
// 用户等级集合
const vipManage = require(path.join(__dirname, '../../models/music_db/vip_grade.js'))
//  用户评论集合
const commentManage = require(path.join(__dirname, '../../models/music_db/comment.js'))
const { queryToken, verifyToken } = require('../../utils/permission')
const util = require('../../utils/index')
const router = express.Router()

const jwToken = require('jsonwebtoken')

const SUCCESS = '00000'
const ERROR = '99998'
const NOLOGIN = '99997'
const secret = 'xzw'
function handData(value) {
  return JSON.parse(JSON.stringify(value))
}

function signToken(_id) {
  return new Promise((resolve, reject) => {
    let token = jwToken.sign({ _id }, secret)
    userManage.updateOne({ _id }, { token }).then(
      res => {
        resolve(token)
      },
      () => reject()
    )
  })
}

// 新增系统用户
router.post('/manage/adduser', queryToken, verifyToken, async (request, response, next) => {
  // 参数
  let { account } = request.body
  // 查询是否注册
  await userManage.findOne({ account }).then(value => {
    if (value) {
      next(['账号已经被注册', ERROR])
      return Promise.reject('账号已经被注册')
    } else {
      return Promise.resolve()
    }
  })
  // 新增
  console.log('xinzeng')
  const usermanage = new userManage({ ...request.body })
  usermanage.save().then(
    data => {
      response.json({
        code: SUCCESS,
        data: null
      })
      console.log('保存成功', data)
    },
    err => {
      console.log(err)
      next(['保存失败'])
    }
  )
})

// 后管系统用户登录验证
router.post('/manage/login', (request, response, next) => {
  let { account, password } = request.body
  userManage
    .findOne({ account, password })
    .then(value => {
      if (value) {
        signToken(value._id)
          .then(token => {
            response.json({
              code: SUCCESS,
              data: {
                ...handData(value),
                token
              }
            })
          })
          .catch(() => next())
      } else {
        next(['账号或密码错误', ERROR])
      }
    })
    .catch(err => next())
})

//退出登录
router.post('/manage/logout/:userNo', (request, response, next) => {
  let { userNo } = request.params
  userManage.findOneAndUpdate({ _id: userNo }, { token: '' }).then(
    () => {
      response.json({
        code: SUCCESS,
        data: null
      })
    },
    () => {
      next(['登出失败'])
    }
  )
})

// 查询系统用户列表
router.get('/manage/user-list', (request, response, next) => {
  let { page = 0, pageSize = 10 } = request.query
  const regFn = arr => {
    const params = {}
    arr.forEach(key => {
      if (!request.body[key]) return
      params[key] = new RegExp(request.body[key], 'i')
    })
    return params
  }
  // 记录查询后的状态（防止查询多次）
  const find = userManage.find()
  // 此处为了获取总数
  find
    .then(totals => {
      // 此处是分页查询  limit：获取多少条数据；skip：跳过多少条数据
      userManage
        .find()
        .sort({ _id: 1 })
        .skip(pageSize * page)
        .limit(pageSize)
        .then(list => {
          response.json({
            code: SUCCESS,
            data: {
              content: list,
              totalLength: totals.length
            }
          })
        })
        .catch(() => next())
    })
    .catch(() => next())
})

// 更新系统用户状态
router.put('/manage/user-status/:userNo/:status', (request, response, next) => {
  let { userNo, status } = request.params
  userManage
    .updateOne({ userNo }, { status })
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(() => next())
})
// 更新系统用户信息
router.put('/manage/user/:userNo', (request, response, next) => {
  let { userNo } = request.params
  let params = request.body
  userManage
    .updateOne({ _id: userNo }, params)
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(() => next())
})
// 删除系统用户
router.delete('/manage/user/:userNo', (request, response, next) => {
  let { userNo } = request.params
  userManage
    .deleteOne({ _id: userNo })
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(err => next([err.message]))
})
// 更新系统用户头像
router.put('/manage/user-avatar', (request, response, next) => {
  let { userNo, img_url } = request.body
  userManage
    .updateOne({ _id: userNo }, { img_url })
    .then(() => {
      userManage.findOne({ _id: userNo }).then(data => {
        response.json({
          code: SUCCESS,
          data
        })
      })
    })
    .catch(() => next())
})

// 查询客户端用户
router.get('/manage/client/user-list', (request, response, next) => {
  let { page = 0, pageSize = 10 } = request.query
  page = Number(page)
  pageSize = Number(pageSize)
  const regFn = arr => {
    const params = {}
    arr.forEach(key => {
      if (!request.query[key]) return
      params[key] = new RegExp(request.query[key], 'i')
    })
    return params
  }
  // 记录查询后的状态（防止查询多次）
  const find = userClient.find(regFn(['nickname', 'account', 'signature']))
  // 此处为了获取总数
  find
    .then(totals => {
      // 此处是分页查询  limit：获取多少条数据；skip：跳过多少条数据
      userClient
        .aggregate([
          {
            $lookup: {
              from: 'vip_grades',
              localField: 'userNo',
              foreignField: 'userNo',
              as: 'vipGrade'
            }
          },
          { $unwind: '$vipGrade' },
          { $project: { _id: 0} },
          {
            $match: regFn(['nickname', 'account', 'signature'])
          }
        ])
        .sort({ _id: 1 })
        .skip(pageSize * page)
        .limit(pageSize)
        .then(list => {
          response.json({
            code: SUCCESS,
            data: {
              content: list,
              totalLength: totals.length
            }
          })
        })
        .catch(() => next())
    })
    .catch(() => next())
})
// 编辑客户端用户
router.post('/manage/edit-clientuser/:userNo', (request, response, next) => {
  let { userNo } = request.params
  userClient
    .updateOne({ userNo }, { ...request.body, vipGrade:0 })
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(() => next())
})
// 新增客户端用户
router.post('/manage/add-clientuser', async (request, response, next) => {
  // 参数
  let { account } = request.body
  // 查询是否注册
  await userClient.findOne({ account }).then(value => {
    if (value) {
      next(['账号已经被注册', ERROR])
      return Promise.reject('账号已经被注册')
    } else {
      return Promise.resolve()
    }
  })
  // 还没有设置密账号格式码验证
  let user = new userClient({
    ...request.body
  })
  user
    .save()
    .then(data => {
      response.json({
        code: SUCCESS,
        data: null
      })
      console.log('新增成功', data)
    })
    .catch(() => next())
})
// 删除客户端用户
router.delete('/manage/clientuser/:userNo', (request, response, next) => {
  let { userNo } = request.params
  userClient
    .deleteOne({ userNo })
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(() => next())
})

// 编辑歌手
router.post('/manage/edit-songer/:songerNo', (request, response, next) => {
  let { songerNo } = request.params
  songerManage
    .updateOne({ _id: songerNo }, request.body)
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(() => next())
})
// 新增歌手
router.post('/manage/add-songer', (request, response, next) => {
  let songer = new songerManage({
    ...request.body
  })
  songer
    .save()
    .then(data => {
      response.json({
        code: SUCCESS,
        data: null
      })
      console.log('新增成功', data)
    })
    .catch(() => next())
})
// 分页查询歌手列表
router.get('/manage/songer-list', (request, response, next) => {
  let { page = 0, pageSize = 10 } = request.query
  page=Number(page)
  pageSize = Number(pageSize)
  const regFn = arr => {
    const params = {}
    arr.forEach(key => {
      let key1 = key.split('$')[0]
      let key2 = key.split('$')[1]
      if (!request.query[key1]) return
      if (!key2) {
        params[key1] = new RegExp(request.query[key1], 'i')
      } else if (key2 == 'arr') {
        params[key1] = request.query[key1]
      }
    })
    return params
  }
  // 记录查询后的状态（防止查询多次）
  const find = songerManage.find(regFn(['name', 'songerNo', 'style$arr']))
  // 此处为了获取总数
  find
    .then(totals => {
      // 此处是分页查询  limit：获取多少条数据；skip：跳过多少条数据
      songerManage
        .find(regFn(['name', 'songerNo', 'style$arr']))
        .sort({ _id: 1 })
        .skip(pageSize * page)
        .limit(pageSize)
        .then(list => {
          response.json({
            code: SUCCESS,
            data: {
              content: list,
              totalLength: totals.length
            }
          })
        })
        .catch(() => next())
    })
    .catch(() => next())
})
// 删除歌手
router.delete('/manage/songer/:songerNo', (request, response, next) => {
  let { songerNo } = request.params
  songerManage
    .deleteOne({ _id: songerNo })
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(() => next())
})

// 编辑歌歌单
router.post('/manage/edit-songlist/:songlistNo', (request, response, next) => {
  let { songlistNo } = request.params
  songListManage
    .updateOne({ _id: songlistNo }, request.body)
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(() => next())
})
// 新增歌单
router.post('/manage/add-songlist', (request, response, next) => {
  let songer = new songListManage({
    ...request.body
  })
  songer
    .save()
    .then(data => {
      response.json({
        code: SUCCESS,
        data: null
      })
      console.log('新增成功', data)
    })
    .catch(() => next())
})
// 分页查询歌单列表
router.get('/manage/songlist-list', (request, response, next) => {
  let { page = 0, pageSize = 10, paging = false } = request.query
  page = Number(page)
  pageSize = Number(pageSize)
  if (paging) pageSize = 10000 // 暂时这么处理
  const regFn = arr => {
    const params = {}
    arr.forEach(key => {
      let key1 = key.split('$')[0]
      let key2 = key.split('$')[1]
      if (!request.query[key1]) return
      if (!key2) {
        params[key1] = new RegExp(request.query[key1], 'i')
      } else if (key2 == 'arr') {
        params[key1] = request.query[key1]
      }
    })
    return params
  }
  // 记录查询后的状态（防止查询多次）
  const find = songListManage.find(regFn(['title', 'songlistNo', 'style$arr']))
  // 此处为了获取总数
  find
    .then(totals => {
      // 此处是分页查询  limit：获取多少条数据；skip：跳过多少条数据
      songListManage
        .find(regFn(['title', 'songlistNo', 'style$arr']))
        .sort({ _id: 1 })
        .skip(pageSize * page)
        .limit(pageSize)
        .then(list => {
          response.json({
            code: SUCCESS,
            data: {
              content: list,
              totalLength: totals.length
            }
          })
        })
        .catch(() => next())
    })
    .catch(() => next())
})
// 删除歌单
router.delete('/manage/songlist/:songListNo', (request, response, next) => {
  let { songListNo } = request.params
  songListManage
    .deleteOne({ _id: songListNo })
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(() => next())
})

// 编辑歌歌曲
router.post('/manage/edit-song/:songNo', (request, response, next) => {
  let { songNo } = request.params
  let params = {}
  Object.keys(request.body).forEach(key => {
    if (key !== '_id') params[key] = request.body[key]
  })
  songManage
    .findOneAndUpdate({ _id: songNo }, params, { new: true })
    .then(data => {
      if (data) {
        response.json({
          code: SUCCESS,
          data: null
        })
      } else {
        next(['歌曲不存在', ERROR])
      }
    })
    .catch(() => next())
})
// 新增歌曲
router.post('/manage/add-song', (request, response, next) => {
  let song = new songManage({
    ...request.body
  })
  song
    .save()
    .then(data => {
      response.json({
        code: SUCCESS,
        data: null
      })
      console.log('新增成功', data)
    })
    .catch(() => next())
})
// 分页查询歌曲列表
router.get('/manage/song-list', (request, response, next) => {
  let { page = 0, pageSize = 10 } = request.query
  page=Number(page)
  pageSize = Number(pageSize)
  const regFn = arr => {
    const params = {}
    arr.forEach(key => {
      if (!request.query[key]) return
      params[key] = new RegExp(request.query[key], 'i')
    })
    return params
  }
  console.log(regFn(['songName', 'songlistNo', 'songerNo']))
  // 记录查询后的状态（防止查询多次）
  const find = songManage.find(regFn(['songName', 'songlistNo', 'songerNo']))
  // 此处为了获取总数
  find
    .then(totals => {
      // 此处是分页查询  limit：获取多少条数据；skip：跳过多少条数据
      songManage
        .aggregate([
          {
            $lookup: {
              from: 'songers',
              localField: 'songerNo',
              foreignField: 'songerNo',
              as: 'songer'
            }
          },
          { $unwind: '$songer' },
          { $addFields: { songerName: '$songer.name' } },
          {
            $match: regFn(['songName', 'songlistNo', 'songerNo'])
          }
        ])
        .sort({ _id: 1 })
        .skip(pageSize * page)
        .limit(pageSize)
        .then(list => {
          response.json({
            code: SUCCESS,
            data: {
              content: list,
              totalLength: totals.length
            }
          })
        })
        .catch(() => next(22))
    })
    .catch(() => next(11))
})
// 查询所有歌曲列表
router.get('/manage/song-list-all', (request, response, next) => {
  const regFn = arr => {
    const params = {}
    arr.forEach(key => {
      if (!request.query[key]) return
      params[key] = new RegExp(request.query[key], 'i')
    })
    return params
  }
  songManage
    .aggregate([
      {
        $lookup: {
          from: 'songers',
          localField: 'songerNo',
          foreignField: 'songerNo',
          as: 'songer'
        }
      },
      {
        $lookup: {
          from: 'song_lists',
          localField: 'songlistNo',
          foreignField: 'songlistNo',
          as: 'songlist'
        }
      },
      { $unwind: '$songer' },
      { $unwind: '$songlist' },
      { $addFields: { songerName: '$songer.name' } },
      { $addFields: { songlistName: '$songlist.title' } },
      {
        $match: regFn(['songName', 'songlistNo', 'songerNo'])
      }
    ])
    .sort({ _id: 1 })
    .then(list => {
      response.json({
        code: SUCCESS,
        data: {
          content: list
        }
      })
    })
    .catch(() => next(22))
})
// 删除歌曲
router.delete('/manage/song/:songNo', (request, response, next) => {
  let { songNo } = request.params
  songManage
    .deleteOne({ _id: songNo })
    .then(() => {
      response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(() => next())
})

// 编辑轮播图
router.post('/manage/carousel', (request, response, next) => {
  carouselManage.find().then(value => {
    if (!value.length) {
      // 新增
      const carousel = new carouselManage(request.body)
      carousel
        .save()
        .then(() => {
          response.json({
            code: SUCCESS,
            data: null
          })
        })
        .catch(() => next())
    } else {
      // 编辑
      carouselManage
        .updateOne({ carouselNo: value[0].carouselNo }, request.body)
        .then(() => {
          response.json({
            code: SUCCESS,
            data: null
          })
        })
        .catch(() => next())
    }
  })
})
// 查询轮播图
router.get('/manage/carousel', (request, response, next) => {
  carouselManage
    .findOne()
    .then(value => {
      response.json({
        code: SUCCESS,
        data: value
      })
    })
    .catch(() => next())
})

// 搜索
router.get('/manage/search', (request, response, next) => {
  let { page = 0, pageSize = 10, type = 0 } = request.query // type:0,歌曲,1,歌手
  let params = {}
  if (type == 0) {
    params.songName = new RegExp(request.query.keyword, 'i')
  } else if (type == 1) {
    params.songerName = new RegExp(request.query.keyword, 'i')
  }
  console.log(params)
  // 记录查询后的状态（防止查询多次）
  const find = songManage.aggregate([
    {
      $lookup: {
        from: 'songers',
        localField: 'songerNo',
        foreignField: 'songerNo',
        as: 'songer'
      }
    },
    { $unwind: '$songer' },
    { $addFields: { songerName: '$songer.name' } },
    {
      $match: params
    }
  ])
  // 此处为了获取总数
  find
    .then(totals => {
      // 此处是分页查询  limit：获取多少条数据；skip：跳过多少条数据
      songManage
        .aggregate([
          {
            $lookup: {
              from: 'songers',
              localField: 'songerNo',
              foreignField: 'songerNo',
              as: 'songer'
            }
          },
          { $unwind: '$songer' },
          { $addFields: { songerName: '$songer.name' } },
          {
            $match: params
          }
        ])
        .sort({ _id: 1 })
        .skip(pageSize * page)
        .limit(pageSize)
        .then(list => {
          response.json({
            code: SUCCESS,
            data: {
              content: list,
              totalLength: totals.length
            }
          })
        })
        .catch(() => next(22))
    })
    .catch(() => next(11))
})
// 更新vip等级集合(这里的更新和客户端的更新不一样，所以要分开写)
router.put('/manage/update-vip/:userNo',(request,response,next)=>{
  vipManage.updateOne({userNo:request.params.userNo},request.body).then(()=>{
    return response.json({
      code:SUCCESS,
      data:null
    })
  }).catch(err=>{
    next(err)
  })
})
/**
 * 传参：
 * @param {string} nickname
 * @param {string} content
 * @param {number} page
 * @param {number} pageSize
 */
// 查询评论
router.get('/manage/comment', (request, response, next) => {
  let { page = 0, pageSize = 10 } = request.query
  page=Number(page)
  pageSize=Number(pageSize)
  commentManage
    .aggregate([
      {
        $lookup: {
          from: 'user_manages',
          localField: 'userNo',
          foreignField: 'userNo',
          as: 'userinfor'
        }
      },
      { $unwind: '$userinfor' },
      { $addFields: { nickname: '$userinfor.nickname' } },
      {
        $match: util.regFn(['nickname', 'content'], { reqParams: request.query })
      }
    ])
    .then(totals => {
      commentManage
        .aggregate([
          {
            $lookup: {
              from: 'user_manages',
              localField: 'userNo',
              foreignField: 'userNo',
              as: 'userinfor'
            }
          },
          { $unwind: '$userinfor' },
          { $addFields: { nickname: '$userinfor.nickname' } },
          {
            $match: util.regFn(['nickname', 'content'], { reqParams: request.query })
          }
        ])
        .sort({ commentTime: 1 })
        .skip(pageSize * page)
        .limit(pageSize)
        .then(list => {
          return response.json({
            code: SUCCESS,
            data: {
              content: list,
              totalLength: totals.length
            }
          })
        })
        .catch(err => next(err))
    })
    .catch(err => next(err))
  
})
module.exports = router
